// src/store/models/login.js
import axios from "axios"
import JSEncrypt from 'jsencrypt'

const api = axios.create({
    baseURL: 'http://localhost:8000', // 根据您的后端地址修改
    timeout: 7000,
    headers: {
        'Content-Type': 'application/json'
    }
})

const state = {
    token: '',
    userid: '',
    username: '',
    role: ''
}

const mutations = {
    SET_TOKEN(state, token) {
        state.token = token
        if (token) {
            localStorage.setItem('access_token', token)
        } else {
            localStorage.removeItem('access_token')
        }
    },
    SET_USERID(state, userid) {
        state.userid = userid
        if (userid) {
            localStorage.setItem('user_id', userid)
        } else {
            localStorage.removeItem('user_id')
        }
    },
    SET_USERNAME(state, username) {
        state.username = username
        if (username) {
            localStorage.setItem('user_name', username)
        } else {
            localStorage.removeItem('user_name')
        }
    },
    SET_ROLE(state, role) {
        state.role = role
        if (role) {
            localStorage.setItem('role', role)
        } else {
            localStorage.removeItem('role')
        }
    },
    CLEAR_AUTH(state) {
        state.token = ''
        state.userid = ''
        state.username = ''

        localStorage.removeItem('access_token')
        localStorage.removeItem('user_id')
        localStorage.removeItem('user_name')
        localStorage.removeItem('role')
        localStorage.removeItem('public_key')
    }
}

const actions = {
    async login({commit}, loginForm) {
        // 登录逻辑
        try {
            // 获取已处理过的公钥
            const publicKey = localStorage.getItem('public_key')

            // 直接在 login 函数内实现 OAEP 填充加密逻辑
            try {
                // 将 PEM 格式转换为 ArrayBuffer
                const binaryDerString = atob(publicKey
                    .replace('-----BEGIN PUBLIC KEY-----', '')
                    .replace('-----END PUBLIC KEY-----', '')
                    .replace(/\s/g, ''))

                const binaryDer = new ArrayBuffer(binaryDerString.length)
                const bufView = new Uint8Array(binaryDer)
                for (let i = 0, strLen = binaryDerString.length; i < strLen; i++) {
                    bufView[i] = binaryDerString.charCodeAt(i)
                }

                // 导入公钥
                const cryptoKey = await crypto.subtle.importKey(
                    'spki',
                    binaryDer,
                    {
                        name: 'RSA-OAEP',
                        hash: 'SHA-256'
                    },
                    false,
                    ['encrypt']
                )

                // 加密数据
                const encodedText = new TextEncoder().encode(loginForm['password'])
                const encrypted = await crypto.subtle.encrypt(
                    {
                        name: 'RSA-OAEP'
                    },
                    cryptoKey,
                    encodedText
                )

                // 转换为 Base64 字符串
                loginForm['password'] = btoa(String.fromCharCode(...new Uint8Array(encrypted)))
            } catch (encryptError) {
                console.error('OAEP 加密失败:', encryptError)
                throw new Error('密码加密失败')
            }

            console.log('----------')
            console.log(loginForm)
            console.log(typeof loginForm['password'])

            const response = await api.post('/login/login', loginForm)

            // 提交多个 mutations
            if (response.data.access_token) {
                commit('SET_TOKEN', response.data.access_token)
            }

            if (response.data.username) {  // 修复条件判断
                commit('SET_USERNAME', response.data.username)
            }
            if (response.data.userid) {
                commit('SET_USERID', response.data.userid)
            }
            if (response.data.role) {
                commit('SET_ROLE', response.data.role)
            }

            // 返回响应数据供组件使用
            return response.data
        } catch (error) {
            console.error("登录失败：", error)
            throw error
        }
    },

    // 登出功能
    logout({commit}) {
        commit('CLEAR_AUTH')

        // 如果需要调用后端登出接口，可以在这里添加
    }
}

const getters = {
    isAuthenticated: state => !!state.token,
    username: state => state.username,
    userid: state => state.userid,
    token: state => state.token
}

// 添加 namespaced 属性，使模块具有命名空间
export default {
    namespaced: true, // 启用命名空间
    state,
    mutations,
    actions,
    getters
}
